#include "memPool_t.h"
using namespace std;

memPool_t::memPool_t() {
	constructPool(1);
}

memPool_t::memPool_t(int numPages) {
	numPages = numPages > 0 ? numPages : 1;
	constructPool(numPages);
}

memPool_t::~memPool_t() {
	list<memPage_t*>::iterator i = m_memPages.begin();
	while (i != m_memPages.end()) {
		delete *i;
		i++;
	}
}

bool memPool_t::setCurrentPos(int newPos) {
	if (newPos < 0 || newPos > m_capacity) {
		return false;
	}

	int tempPos=0;
	memPage_t* newCurPage = getPageByPosition(newPos, tempPos);

	if (!newCurPage->setCurrentPos(tempPos)) {
		return false;
	}

	m_curPage = newCurPage;
	m_curPos = newPos;

	return true;
}

void memPool_t::createNewPages(int numPages) {
	for (int i=0; i < numPages; i++) {
		memPage_t* page = new memPage_t();
		m_memPages.push_back(page);
		m_capacity += page->getCapacity();
	}
}

/* Private Functions */
void memPool_t::constructPool(int numPages) {
	m_curPos = 0;
	m_actualSize = 0;
	m_capacity = 0;

	createNewPages(numPages);

	m_curPage = getFirstPage();
}

memPage_t* memPool_t::getPageByPosition(int globalPos, int& pagePos) const {
	list<memPage_t*>::const_iterator i = m_memPages.begin();
	pagePos = globalPos;
	while (pagePos >= (*i)->getCapacity()) {
		pagePos -= (*i)->getCapacity();
		i++;
	}
	
	return *i;
}
